import React from 'react'
import { Link } from 'react-router-dom';
import { Upload, Spin, Tooltip, Modal, Icon, Popconfirm, Table, Col, Row, Form, Input, Button, Message, Cascader } from 'antd';
import api from '../../../api/communityManage';
import md5 from 'md5';
import moment from 'moment';
import serverConfig from "../../../utils/config";
const FormItem = Form.Item;

import { reqToken } from "../../../utils/reqTools";

import PanelBox from '../../../components/PanelBox';

import './index.less';
import { RoomForm, InfoForm, BuildForm, FloorForm, QuickForm, DelICForm } from '../../Form/CommunityManage';
import CommunityCascader from '../../Cascader/CommunityCascader';

const pageRouter = '/community/communityPlatform';


class Search extends React.Component {
  constructor(props) {
    super(props);
    let search = props.history.location.search.replace("?", "");
    let paramStrin = search.split("&");
    let result = {};
    paramStrin.forEach(ele => {
      let p = ele.split("=");
      result[p[0]] = p[1];
    })
    if (result.name && result.name.length > 0) {
      result.name = decodeURIComponent(result.name)
      props.onInput({ target: { value: result.name } })
    }
    this.state = {
      main: {
        word: "小区",
        allowCreate: false,
        allowOpenIC: false,
        allowSearch: false,
        loadding: false,
        cascaderValue: result.id ? result.id : null,
        inputValue: result.name
      }
    }
  }
  main = {
    params: {},
    props: {
      user: this.props.user,
      flush: this.props.flush,
      onInput: e => {
        this.props.onInput && this.props.onInput(e);
      },
      onSearch: data => {
        this.props.onSearch && this.props.onSearch(data);
      },
      onOpenIc: () => {
        this.props.onOpenIc && this.props.onOpenIc(this.main.params);
      },
      onCreate: () => {
        this.props.onCreate && this.props.onCreate(this.main.params);
      }
    },
    setMainState: (key, value) => {
      let main = this.state.main;
      main[key] = value;
      this._isMounted && this.setState({
        main
      });
    },
    inputOnChange: e => {
      this.main.params.name = e.target.value;
      this.main.setMainState("inputValue", e.target.value);
      this.main.props.onInput(e);
    },
    communityOnChange: values => {
      this.main.params.ids = values;
      this.main.params.id = values[values.length - 1];
      this.main.props.onSearch(this.main.params);
      let word = ["小区", "大楼", "楼层", "房间"];
      if (values.length >= 2) {
        this.main.setMainState("word", word[values.length - 2]);
        this.main.setMainState("allowCreate", true);
        this.main.setMainState("allowSearch", true);
      } else {
        this.main.setMainState("addTitle", word[0]);
        this.main.setMainState("allowCreate", false);
        this.main.setMainState("allowSearch", false);
      }
      if (values.length > 2) {
        this.main.setMainState("allowOpenIC", true);
      } else {
        this.main.setMainState("allowOpenIC", false);
      }
    }
  }

  componentDidMount = () => {

  }

  componentWillReceiveProps = (nextProps) => {
    if (nextProps.flush && nextProps.flush != this.props.flush) {
      this.main.props.onSearch(this.main.params);
    }
  }

  render() {
    return (
      <Row className="search-box" type="flex" justify="start">
        <Col span="10" className="search-item">
          <Col span="3" className="label">小区</Col>
          <Col span="20" className="content" >
            <CommunityCascader office={true} pid={this.props.user.officeId} defaultValue={this.state.main.cascaderValue} className="community-cascader" maxLevel="5" onChange={this.main.communityOnChange} />
          </Col>
        </Col>
        <Col span="5" className="search-item">
          <Col span="6" className="label">{this.state.main.word + "名称"}</Col>
          <Col span="15" className="content" >
            <Input value={this.state.main.inputValue} onChange={this.main.inputOnChange} disabled={!this.state.main.allowSearch} />
          </Col>
        </Col>
        <Col className="search-item">
          <Button className="button" type="primary" icon="reload" onClick={() => this.props.history.replace(pageRouter)}>清空条件</Button>
        </Col>
        <Col className="search-item">
          <Button className="button" type="primary" icon="plus-circle-o" onClick={this.main.props.onCreate} disabled={!this.state.main.allowCreate}>{"添加" + this.state.main.word}</Button>
        </Col>
        <Col className="search-item">
          <Tooltip placement="topLeft" title="当前小区为搜索条件里面选择的小区">
            <Button className="button" type="primary" icon="bars" onClick={this.main.props.onOpenIc} disabled={!this.state.main.allowOpenIC}>{"管理小区IC卡"}</Button>
          </Tooltip>
        </Col>
      </Row>
    )
  }
}

class ExpandedRow extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      main: {
        data: [],
        loading: false,
      }
    }
  }
  static defaultProps = {
    key: null,
    record: null
  }
  componentWillMount() {
    if (this.props.record != null) {
      this.setObjectState("main", { loadding: true });
      api.get("/community/getIcInfo", { hardEquiId: this.props.record.hardequiid,infoId: this.props.record.infoId }).then(res => {
        this.setObjectState("main", { data: res.data });
        this.setObjectState("main", { loadding: false });
      });
    }
  }
  setObjectState = (key, value) => {
    let keyArray = key.split("\.");
    let first = keyArray[0];
    let o = this.state[first];
    let level = o;
    for (let i = 1; i < keyArray.length; i++) {
      let ele = keyArray[i];
      level = o[ele];
    }
    for (let ele in value) {
      if (value.hasOwnProperty(ele)) {
        level[ele] = value[ele];
      }
    }
    let r = {};
    r[first] = o;
    this.setState(r);
  }
  main = {
  }
  render() {
    let i = 0;
    return (
      <Spin spinning={this.state.main.loading}>
        <Tooltip placement="topLeft" title="IC卡绑定的小区位置">
          <div>
            {this.state.main.data instanceof Array && this.state.main.data.length > 0 ? this.state.main.data.map(item => <p key={i++} className="expanded-row">{(item.parentNames + item.name).replace(/,/ig, "/")}</p>) : <p key={0} className="expanded-row">暂无绑定小区位置</p>}
          </div>
        </Tooltip>
      </Spin>
    )
  };
}

class IcTableClass extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      main: {
        data: [],
        pagination: {
          pageSize: 5
        },
        loading: false,
      },
      search: {
        params: {
          infoId: props.record.id,
          structureId: props.record.structureId
        }
      }
    }
  }
  setObjectState = (key, value) => {
    let keyArray = key.split("\.");
    let first = keyArray[0];
    let o = this.state[first];
    let level = o;
    for (let i = 1; i < keyArray.length; i++) {
      let ele = keyArray[i];
      level = o[ele];
    }
    for (let ele in value) {
      if (value.hasOwnProperty(ele)) {
        level[ele] = value[ele];
      }
    }
    let r = {};
    r[first] = o;
    this.setState(r);
  }
  search = {
    params: {},
    onSearch: (e) => {
      this.setObjectState("main.pagination", { current: 1, });
      let params = this.props.form.getFieldsValue();
      params.pageSize = this.state.main.pagination.pageSize;
      this.search.params = { ...params, ...this.state.search.params, ...this.state.main.pagination };
      this.main.fetch(this.search.params);
    }
  }
  main = {
    del: record => {
      this.setObjectState("main", { loading: true });
      if (this.state.search.params.infoId) {
        api.delete("/community/delIc", { id: this.state.search.params.infoId, hardEquiId: record.hardequiid }).then(res => {
          this.setObjectState("main", { loading: false });
          if (res.code == 0) {
            Message.success("操作成功");
            this.main.fetch();
          }
        }).catch(e => {
          this.setObjectState("main", { loading: false });
          Message.error(e.response.data.error + "(code:" + e.response.data.status + ")");
        });
      } else if (this.state.search.params.structureId) {
        api.delete("/community/delCommunityIc", { id: this.state.search.params.structureId, hardEquiId: record.hardEquiId }).then(res => {
          this.setObjectState("main", { loading: false });
          if (res.code == 0) {
            Message.success("操作成功");
            this.main.fetch();
          }
        }).catch(e => {
          this.setObjectState("main", { loading: false });
          Message.error(e.response.data.error + "(code:" + e.response.data.status + ")");
        });
      }
    },
    handleTableChange: (pagination, filters, sorter) => {
      const pager = { ...this.state.main.pagination };
      pager.current = pagination.current;
      this.setObjectState("main.pagination", pager);
      this.main.fetch({
        ...this.search.params,
        ...this.state.search.params,
        pageSize: pagination.pageSize,
        pageNum: pagination.current,
        sortField: sorter.field,
        sortOrder: sorter.order,
        ...filters,
      });
    },
    fetch: (params) => {
      if (!params) {
        params = { ...this.search.params, ...this.state.search.params };
      }
      if (!params.pageNum) {
        params.pageNum = 1;
      }
      params.pageSize = this.state.main.pagination.pageSize;
      this.setObjectState("main", { loading: true });
      if (params.infoId) {
        api.get('/community/getIc', { ...params }).then(res => {
          const data = res.data || [];
          const pagination = this.state.main.pagination;
          pagination.total = data.total;
          this.setObjectState("main", {
            loading: false,
            data: data.list,
            pagination,
          });
        });
      } else if (params.structureId) {
        api.get('/community/getCommunityIc', { ...params }).then(res => {
          const data = res.data || [];
          const pagination = this.state.main.pagination;
          pagination.total = data.total;
          this.setObjectState("main", {
            loading: false,
            data: data.list,
            pagination,
          });
        });
      }
    }
  }
  componentDidMount() {
    this.main.fetch();
  }
  componentWillReceiveProps = nextProps => {
    if (nextProps.record != this.props.record) {
      this.props.form.resetFields();
      this.setObjectState("main.pagination", { current: 1, });
      this.setObjectState("search.params", {
        infoId: nextProps.record.id,
        structureId: nextProps.record.structureId
      });
      this.search.params = {
        infoId: nextProps.record.id,
        structureId: nextProps.record.structureId
      }
      this.main.fetch();
    }
  }
  render() {
    let columns = [];
    let key = "id";
    let expandedRowRender = {
      expandedRowRender: record => <ExpandedRow record={record} />
    };
    if (this.state.search.params.infoId) {
      columns = [{
        title: 'IC卡编号',
        dataIndex: 'hardequiid',
        width: '40%',
      }, {
        title: '创建时间',
        dataIndex: 'createDate',
        width: '30%',
      }, {
        title: '操作',
        key: 'action',
        render: (text, record) => (
          <span>
            <Popconfirm title="删除IC卡后,此卡就不能开门,并且不可恢复,确定删除" onConfirm={this.main.del.bind(this, record)} okText="是" cancelText="否">
              <a href="javascript:void(0)">删除</a>
            </Popconfirm>
          </span>
        ),
      }];
    } else if (this.state.search.params.structureId) {
      key = "hardEquiId";
      expandedRowRender = {};
      columns = [{
        title: 'IC卡编号',
        dataIndex: 'hardEquiId',
        width: '40%',
      }, {
        title: '创建时间',
        dataIndex: 'createDate',
        width: '30%',
      }, {
        title: '操作',
        key: 'action',
        render: (text, record) => (
          <span>
            <Popconfirm title="删除IC卡后,此卡就不能开门,并且不可恢复,确定删除" onConfirm={this.main.del.bind(this, record)} okText="是" cancelText="否">
              <a href="javascript:void(0)">删除</a>
            </Popconfirm>
          </span>
        ),
      }];
    }
    const { getFieldDecorator } = this.props.form;
    return (
      <Form onSubmit={this.search.onSearch}>
        <Row className="search-box" type="flex" justify="start">
          <Col span="7" className="search-item">
            <Col span="8" className="label">IC卡编号</Col>
            <Col span="15" className="content" >
              {getFieldDecorator('hardEquiId', {
              })(
                <Input placeholder="输入完整的IC卡号" />
                )}
            </Col>
          </Col>
          <Col className="search-item">
            <Button className="button" type="primary" icon="search" htmlType="submit">搜索</Button>
          </Col>
        </Row>
        <Table columns={columns}
          rowKey={key}
          dataSource={this.state.main.data}
          pagination={this.state.main.pagination}
          loading={this.state.main.loading}
          onChange={this.main.handleTableChange}
          {...expandedRowRender}
        />
      </Form>
    );
  }
}

const IcTable = Form.create()(IcTableClass);

class IcUpload extends React.Component {
  state = {
    url: serverConfig.primary + '/api/communityStructureIc/upload',
  }
  componentWillMount() {
    this._isMounted = true;
    this.props.record != null && reqToken().then(res => {
      this._isMounted && this.setState({
        url: serverConfig.primary + '/api/communityStructureIc/upload?token=' + res
      })
    });
  }
  componentWillUnmount() {
    this._isMounted = false;
  }
  componentWillReceiveProps(nextProps) {
    if (nextProps.record != this.props.record) {
      reqToken().then(res => {
        this._isMounted && this.setState({
          url: serverConfig.primary + '/api/communityStructureIc/upload?token=' + res
        })
      });
    }
  }
  render() {
    let props = {
      name: 'file',
      action: this.state.url,
      data: { id: this.props.record.id },
      showUploadList: false,
      beforeUpload: (file, fileList) => {
        console.log(file)
      },
      headers: {
        authorization: 'authorization-text',
      },
      onChange(info) {
        if (info.file.status !== 'uploading') {
          console.log(info.file, info.fileList);
        }
        if (info.file.status === 'done') {
          if (info.file.response.code == 0) {
            Message.success(`导入成功`);
          } else {
            Message.error(info.file.response.message);
          }
        } else if (info.file.status === 'error') {
          Message.error(`${info.file.name} file upload failed.`);
        }
      },
    };
    return (
      <Upload className="upload-button" {...props}>
        <Tooltip placement="topLeft" title="在该位置导入的IC卡可以打开绑定该位置的所有设备（导入IC卡将会清空该位置原有所有IC卡,再添加导入的IC卡,导入文件格式为机器导出的txt文件,每个IC卡占一行）">
          <a href="javascript:void(0)" onClick={this.props.onClick}> 导入IC卡</a>
        </Tooltip>
      </Upload>
    )
  }
}

export default class CommunityManage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      table: {
        filterDropdownVisible: false,
        data: [],
        loading: false
      },
      quick: {
        show: false,
        record: {
          infoId: null
        }
      },
      ic: {
        show: false,
        record: {}
      },
      form: {
        record: {}
      },
      modal: {
        title: null,
        show: false,
      },
      search: {
        flush: false
      },
      main: {
        user: this.props.profile.user
      }
    }
  }
  main = {
    setMainState: (key, value) => {
      let main = this.state.main;
      main[key] = value;
      this.setState({
        main
      });
    },
    reload: () => {
      let url = pageRouter + "?";
      if (this.search.params.ids && this.search.params.ids.length > 0) {
        url = url + "&id=" + this.search.params.ids[this.search.params.ids.length - 1];
      }
      if (this.search.params.name && this.search.params.name.length > 0) {
        url = url + "&name=" + this.search.params.name;
      }
      url = url.replace("?&", "?");
      this.props.history.replace(url);
    }
  }
  table = {
    onSearch: (value) => {
      const searchText = value;
      const reg = new RegExp(searchText, 'gi');
      let table = this.state.table;
      table.filterDropdownVisible = false;
      table.filtered = !!searchText;
      if (this.table.data) {
        table.data = this.table.data.map((record) => {
          const match = record.showName.match(reg);
          if (!match) {
            return null;
          }
          return {
            ...record,
            showName: (
              <span>
                {record.showName.split(reg).map((text, i) => (
                  i > 0 ? [<span className="highlight">{match[0]}</span>, text] : text
                ))}
              </span>
            ),
          };
        }).filter(record => !!record);
      }
      this._isMounted && this.setState({
        table
      });
    },
    save: record => {
      let index = 0;
      if (this.search.params.ids && this.search.params.ids.length > 1) {
        index = this.search.params.ids.length - 2;
      } else {
        return;
      }
      let { form, modal } = this.state;
      let editTitles = ["修改小区", "修改大楼", "修改楼层", "修改房间"];
      let addTitles = ["添加小区", "添加大楼", "添加楼层", "添加房间"];
      let columns = ["officeId", "infoId", "buildId", "floorId"]
      form.record = record || {};
      if (!form.record.officeId) {
        form.record.officeId = this.search.params.ids[1];
        form.record[columns[index]] = this.search.params.ids[this.search.params.ids.length - 1];
      }
      modal.show = true;
      modal.title = record ? editTitles[index] : addTitles[index];
      this.setState({ form, modal });
    },
    del: id => {
      let index = 0;
      if (this.search.params.ids && this.search.params.ids.length > 1) {
        index = this.search.params.ids.length - 2;
      }
      this.del[index](id).then(res => {
        if (res.code != 0) {
          Message.error(res.message);
          return;
        }
        this.search.onSearch(this.search.params);
        Message.success('删除成功！');
      });
      this.main.reload();
    },
    onOpenIc: record => {
      let ic = this.state.ic;
      ic.record = { structureId: record.id };
      ic.show = true;
      this.setState({
        ic
      });
    }
  }
  search = {
    params: {},
    onInput: e => {
      this.search.params.name = e.target.value;
      this.table.onSearch(e.target.value);
    },
    onOpenIc: params => {
      this.search.params.id = params.id;
      this.search.params.ids = params.ids;
      let ids = params.ids;
      let table = this.state.table;
      if (!ids || ids.length < 2) {
        return;
      }
      let ic = this.state.ic;
      ic.show = true;
      ic.record = { id: ids[2] };
      this.setState({
        ic
      });
    },
    onSearch: params => {
      this.search.params.id = params.id;
      this.search.params.ids = params.ids;
      let ids = params.ids;
      let table = this.state.table;
      if (!ids || ids.length < 2) {
        table.data = [];
        this._isMounted && this.setState({
          table
        });
        return;
      }
      table.loading = true;
      table.data = [];
      this._isMounted && this.setState({
        table
      });
      this.select[ids.length - 2](params.id).then(data => {
        table.loading = false;
        table.data = data;
        this.table.data = data;
        this._isMounted && this.setState({
          table
        });
        this.table.onSearch(this.search.params.name);
      }).catch(e => {
        table.loading = false;
        this.setState({
          table
        });
      })
    },
    onCreate: () => {
      this.table.save();
    }
  }
  quick = {
    open: (record) => {
      let quick = this.state.quick;
      quick.show = true;
      record && (record.buildId = record.id);
      this.state.quick.record = record;
      this.setState({
        quick
      });
    },
    onSubmit: (res) => {
      if (res.code == 0) {
        Message.success('操作成功！');
        this.main.reload();
      } else {
        Message.error(res.message);
      }
    },
    onCancel: () => {
      let quick = this.state.quick;
      quick.show = false;
      this.setState({
        quick
      });
    }
  }
  ic = {
    onSubmit: () => {
      let ic = this.state.ic;
      ic.show = false;
      this.setState({
        ic
      });
    },
    onCancel: () => {
      let ic = this.state.ic;
      ic.show = false;
      this.setState({
        ic
      });
    }
  }
  modal = {
    onSubmit: (res) => {
      if (res.code == 0) {
        Message.success('操作成功！');
        this.main.reload();
      } else {
        Message.error(res.message);
      }
    },
    onCancel: () => {
      let modal = this.state.modal;
      modal.show = false;
      this.setState({
        modal
      });
    }
  }

  select = [
    (pid = 1) => new Promise((resolve, reject) => {
      api.get('/community/getCommunity', { office_id: pid }).then(res => {
        const result = res.data || [];
        result.forEach(ele => {
          ele.showName = ele.name
        });
        resolve(result);
      });
    }), (pid = 1) => new Promise((resolve, reject) => {
      api.get('/community/getBuild', { infoId: pid }).then(res => {
        const result = res.data || [];
        result.forEach(ele => {
          ele.showName = ele.name
        });
        resolve(result);
      });
    }), (pid = 1) => new Promise((resolve, reject) => {
      api.get('/community/getFloor', { buildId: pid }).then(res => {
        const result = res.data || [];
        result.forEach(ele => {
          ele.showName = ele.name
        });
        resolve(result);
      });
    }), (pid = 1) => new Promise((resolve, reject) => {
      api.get('/community/room', { floorId: pid }).then(res => {
        const result = res.data || [];
        result.forEach(ele => {
          ele.showName = ele.name
        });
        resolve(result);
      });
    })
  ]

  del = [
    id => {
      return api.delete('/community/info/del', { id });
    },
    id => {
      return api.delete('/community/build/del', { buildId: id });
    },
    id => {
      return api.delete('/community/floor/del', { floorId: id });
    },
    id => {
      return api.delete('/community/room/del', { houseId: id });
    },
  ]

  componentWillMount = () => {
    this._isMounted = true;
  }
  componentDidMount = () => {
  }
  componentWillUnmount() {
    this._isMounted = false
  }

  upload = {
    data: {},
    importRow: (record) => {
      this.upload.data.id = record.id;
    }
  }

  render() {
    let record = this.upload.record;
    const getForm = () => {
      let form = [
        <InfoForm record={this.state.form.record} clear={this.state.modal.show} onSubmit={this.modal.onSubmit} onCancel={this.modal.onCancel} />,
        <BuildForm record={this.state.form.record} clear={this.state.modal.show} onSubmit={this.modal.onSubmit} onCancel={this.modal.onCancel} />,
        <FloorForm record={this.state.form.record} clear={this.state.modal.show} onSubmit={this.modal.onSubmit} onCancel={this.modal.onCancel} />,
        <RoomForm record={this.state.form.record} clear={this.state.modal.show} onSubmit={this.modal.onSubmit} onCancel={this.modal.onCancel} />
      ];
      let index = 0;
      if (this.search.params.ids && this.search.params.ids.length > 1) {
        index = this.search.params.ids.length - 2;
      }
      return form[index];
    }
    const columns = {
      info: [{
        title: '小区名称',
        dataIndex: 'showName',
        width: '20%',
      }, {
        title: '所属区域',
        dataIndex: 'areaName',
        width: '20%',
      }, {
        title: '小区电话',
        dataIndex: 'phone',
        width: '20%',
      }, {
        title: '创建时间',
        dataIndex: 'createDate',
        width: '20%',
      }, {
        title: '操作',
        key: 'action',
        render: (text, record) => (
          <span>
            <a href="javascript:void(0)" onClick={this.table.save.bind(this, record)}>编辑</a>
            <span className="ant-divider" />
            <IcUpload record={record} onClick={this.upload.importRow.bind(this, record)} />
            <span className="ant-divider" />
            <a href="javascript:void(0)" onClick={this.table.onOpenIc.bind(this, record)} >查看IC卡</a>
            <span className="ant-divider" />
            <Popconfirm title="删除小区会删除小区下面的大楼、楼层、房间,并解绑和其绑定的设备,还会解除和其房间绑定的业主及家人,不可恢复,确定删除?" onConfirm={this.table.del.bind(this, record.id)} okText="是" cancelText="否">
              <a href="javascript:void(0)">删除</a>
            </Popconfirm>
          </span>
        ),
      }],
      build: [{
        title: '大楼名称',
        dataIndex: 'showName',
        width: '25%',
      }, {
        title: '大楼序列',
        dataIndex: 'sort',
        width: '25%',
      }, {
        title: '创建时间',
        dataIndex: 'createDate',
        width: '25%',
      }, {
        title: '操作',
        key: 'action',
        render: (text, record) => (
          <span>
            <a href="javascript:void(0)" onClick={this.table.save.bind(this, record)} >编辑</a>
            <span className="ant-divider" />
            <a href="javascript:void(0)" onClick={this.quick.open.bind(this, record)} >快速创建</a>
            <span className="ant-divider" />
            <IcUpload record={record} onClick={this.upload.importRow.bind(this, record)} />
            <span className="ant-divider" />
            <a href="javascript:void(0)" onClick={this.table.onOpenIc.bind(this, record)} >查看IC卡</a>
            <span className="ant-divider" />
            <Popconfirm title="删除大楼会删除大楼下面的楼层、房间,并解绑和其绑定的设备,还会解除和其房间绑定的业主及家人,不可恢复,确定删除?" onConfirm={this.table.del.bind(this, record.id)} okText="是" cancelText="否">
              <a href="javascript:void(0)">删除</a>
            </Popconfirm>
          </span>
        ),
      }],
      floor: [{
        title: '楼层名称',
        dataIndex: 'showName',
        width: '25%',
      }, {
        title: '楼层序列',
        dataIndex: 'sort',
        width: '25%',
      }, {
        title: '创建时间',
        dataIndex: 'createDate',
        width: '25%',
      }, {
        title: '操作',
        key: 'action',
        render: (text, record) => (
          <span>
            <a href="javascript:void(0)" onClick={this.table.save.bind(this, record)} >编辑</a>
            <span className="ant-divider" />
            <IcUpload record={record} onClick={this.upload.importRow.bind(this, record)} />
            <span className="ant-divider" />
            <a href="javascript:void(0)" onClick={this.table.onOpenIc.bind(this, record)} >查看IC卡</a>
            <span className="ant-divider" />
            <Popconfirm title="删除楼层会删除楼层下面的房间,并解绑和其绑定的设备,还会解除和其房间绑定的业主及家人,不可恢复,确定删除?" onConfirm={this.table.del.bind(this, record.id)} okText="是" cancelText="否">
              <a href="javascript:void(0)">删除</a>
            </Popconfirm>
          </span>
        ),
      }],
      room: [{
        title: '房间名',
        dataIndex: 'showName',
        width: '20%',
      }, {
        title: '房间序列',
        dataIndex: 'sort',
        width: '20%',
      }, {
        title: '房间每月费用',
        dataIndex: 'monthCost',
        width: '20%',
      }, {
        title: '创建时间',
        dataIndex: 'createDate',
        width: '20%',
      }, {
        title: '操作',
        key: 'action',
        render: (text, record) => (
          <span>
            <a href="javascript:void(0)" onClick={this.table.save.bind(this, record)} >编辑</a>
            <span className="ant-divider" />
            <IcUpload record={record} onClick={this.upload.importRow.bind(this, record)} />
            <span className="ant-divider" />
            <a href="javascript:void(0)" onClick={this.table.onOpenIc.bind(this, record)} >查看IC卡</a>
            <span className="ant-divider" />
            <Popconfirm title="删除房间会解除和其绑定的业主及家人,并解除和其绑定的设备,不可恢复,确定删除?" onConfirm={this.table.del.bind(this, record.id)} okText="是" cancelText="否">
              <a href="javascript:void(0)">删除</a>
            </Popconfirm>
          </span>
        ),
      }]
    }
    const getTable = () => {
      let table = [
        <Table columns={columns.info} rowKey={'id'} dataSource={this.state.table.data} pagination={false} loading={this.state.table.loading} />,
        <Table columns={columns.build} rowKey={'id'} dataSource={this.state.table.data} pagination={false} loading={this.state.table.loading} />,
        <Table columns={columns.floor} rowKey={'id'} dataSource={this.state.table.data} pagination={false} loading={this.state.table.loading} />,
        <Table columns={columns.room} rowKey={'id'} dataSource={this.state.table.data} pagination={false} loading={this.state.table.loading} />
      ];
      let index = 0;
      if (this.search.params.ids && this.search.params.ids.length > 1) {
        index = this.search.params.ids.length - 2;
      }
      return table[index];
    }

    return (
      <div>
        <Search history={this.props.history} flush={this.state.search.flush} user={this.state.main.user} onSearch={this.search.onSearch} onInput={this.search.onInput} onCreate={this.search.onCreate} onOpenIc={this.search.onOpenIc} />
        <Modal
          title={this.state.modal.title}
          maskClosable={false}
          visible={this.state.modal.show}
          onCancel={this.modal.onCancel}
          wrapClassName="vertical-center-modal"
          width="800"
          style={{ height: 'auto' }}
          footer={null}
        >
          {getForm()}
        </Modal>
        <Modal
          title="快速添加楼层房间"
          visible={this.state.quick.show}
          maskClosable={false}
          onCancel={this.quick.onCancel}
          wrapClassName="vertical-center-modal"
          width="800"
          style={{ height: 'auto' }}
          footer={null}
        >
          <QuickForm record={this.state.quick.record} clear={this.state.quick.show} onSubmit={this.quick.onSubmit} onCancel={this.quick.onCancel} />
        </Modal>
        <Modal
          title="IC卡管理"
          visible={this.state.ic.show}
          maskClosable={false}
          onCancel={this.ic.onCancel}
          wrapClassName="vertical-center-modal"
          width="800"
          style={{ height: 'auto' }}
          footer={null}
        >
          <IcTable record={this.state.ic.record} clear={this.state.ic.show} onSubmit={this.ic.onSubmit} onCancel={this.ic.onCancel} />
        </Modal>
        <PanelBox>
          {getTable()}
        </PanelBox>
      </div>
    )
  }
}







